package cn.utils;

import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Logger;

public class BaseUtils {
    static private Properties pro = null;
    static {
        pro = new Properties();
        try {
            pro.load(BaseUtils.class.getClassLoader().getResourceAsStream("settings.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 随机100次，返回一个随机数
     * @param length 范围
     * @return 返回随机数
     */
    public static Integer randNum(int length) {
        int rand = 0;
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < 100; i++) {
            rand = random.nextInt(length);
        }

        return rand;
    }


    /**
     * 根据键名获取配置文件内容
     * @param keyword
     * @return
     */
    public static Object getProperties(String keyword) {
        return pro.get(keyword);
    }

    public static String getProString(String keyword) {
        return (String) getProperties(keyword);
    }

    public static String getRandomNum(int length) {
        String num = "0123456789";
        String verify = "";

        for (int i = 0; i < length; i++) {
            Integer index = randNum(num.length());
            verify += num.charAt(index);
        }
        return verify;
    }

    public static String getTime(int day, String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(5, day);
        Date time = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = sdf.format(time);
        return date;
    }

    public static String getTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = "";
        try {
            Date date = new Date(Long.valueOf(time));
            str = sdf.format(date);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return str;
    }
    public static String getOrderNo(int kind) {
        StringBuffer sb = new StringBuffer(kind + getRandomNum(6));
        String millis = String.valueOf(System.currentTimeMillis());
        for (int i = 0; i < 6; i++) {
            Integer index = randNum(millis.length());
            sb.append(millis.charAt(index));
        }
//        sb.append(millis.substring(millis.length() - 6, millis.length()));
        return String.valueOf(sb);
    }

}
